package menu

import (
	"context"

	"mall/common/modelx"
	"mall/common/utils/pointy"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMenuByIdLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetMenuByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMenuByIdLogic {
	return &GetMenuByIdLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetMenuByIdLogic) GetMenuById(in *backend.IDReq) (*backend.MenuInfo, error) {
	if in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	res, err := l.svcCtx.SysMenu.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.MenuInfo{
		Id:        pointy.GetPointer(res.ID),
		ParentId:  pointy.GetPointer(res.ParentID),
		Type:      pointy.GetPointer(uint32(res.MenuType)),
		Level:     pointy.GetPointer(uint32(res.MenuLevel)),
		Path:      pointy.GetPointer(res.Path),
		Name:      pointy.GetPointer(res.Name),
		Redirect:  pointy.GetPointer(res.Redirect),
		Component: pointy.GetPointer(res.Component),
		Status:    pointy.GetPointer(uint32(res.Status)),
		Sort:      pointy.GetPointer(uint32(res.Sort)),
		CreatedAt: pointy.GetPointer(modelx.FormatTime(res.CreatedAt, "")),
		UpdatedAt: pointy.GetPointer(modelx.FormatTime(res.UpdatedAt, "")),
		DeletedAt: pointy.GetPointer(modelx.FormatNullDotTime(res.DeletedAt, "")),
		Meta: &backend.MenuMeta{
			Title:              pointy.GetPointer(res.Title),
			Icon:               pointy.GetPointer(res.Icon),
			HideMenu:           pointy.GetPointer(uint32(res.HideMenu)),
			HideChildrenInMenu: pointy.GetPointer(uint32(res.HideChildrenInMenu)),
			HideBreadcrumb:     pointy.GetPointer(uint32(res.HideBreadcrumb)),
			HideTab:            pointy.GetPointer(uint32(res.HideTab)),
			IgnoreKeepAlive:    pointy.GetPointer(uint32(res.IgnoreKeepAlive)),
			Affix:              pointy.GetPointer(uint32(res.Affix)),
			FrameSrc:           pointy.GetPointer(res.FrameSRC),
			CarryParam:         pointy.GetPointer(uint32(res.CarryParam)),
			DynamicLevel:       pointy.GetPointer(uint32(res.DynamicLevel)),
			RealPath:           pointy.GetPointer(res.RealPath),
		},
	}, nil
}
